<?php
namespace app\admin\controller;

use app\admin\model\BlogArticle as ArticleModel;
use app\admin\model\BlogCategory as CategoryModel;
use think\Request;

class BlogArticle extends Base
{
    protected $model;
    protected $request;
    protected $categories;


    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->request = $request;

        $this->categories = CategoryModel::where(['template'=>1])->column('id, name');

        $this->model = new ArticleModel();
    }

    public function index($page = 1)
    {
        $param = $this->request->get();

        $cid = isset($param['cid']) ? $param['cid']: 0;
        $top = isset($param['top']) ? $param['top']: 0;
        $status = isset($param['status']) ? $param['status']: 0;
        $title = isset($param['title']) ? $param['title']: 0;
        $num_of_page = isset($param['num_of_page']) ? $param['num_of_page']: 10;
        
        $this->assign('page', $page);
        $this->assign('cid', $cid);
        $this->assign('top', $top);
        $this->assign('status', $status);
        $this->assign('title', $title);
        $this->assign('num_of_page', $num_of_page);
        
        $map = [];
        $title ? $map['title'] = ['like', '%' . $title . '%'] : '';
        
        $field = 'id,cid,thumb,title,pubtime,sort,status,top,clicks';
        $result = $this->model->getLists($cid, $page, $num_of_page, $top, $status, $map, $field);
                 
        $this->assign('counts', $result['counts']);
        $this->assign('pages', $result['pages']);
        $this->assign('data', $result['lists']);

        $this->assign('categories', $this->categories);

        return $this->fetch();
    }

    /**
     * 上下线与置顶
     */
    public function topStatus()
    {
        if ($this->request->isAjax()) {
            $param =input('post.');
            
            $result = $this->model->save([$param['field']=>$param['value']], ['id'=>$param['id']]);

            if ($result===false) {
                return ['code' => 0];
            } else {
                return ['code' => 2];
            }
        }
    }

    /**
     * 软删除
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $id =input('post.')['id'];

            $result = true;

            if (is_array($id)) {
                foreach ($id as $val) {
                    $list[] = ['id'=>intval($val), 'isdel'=>1];
                }
                $result = $this->model->saveAll($list);
            } else {
                $result = $this->model->save(['isdel'=>1], ['id'=>$id]);
            }

            if ($result===false) {
                return ['code' => 0, 'msg' => config('msg.1002')];
            } else {
                return ['code' => 2, 'msg' => config('msg.1001')];
            }
        }
    }

    /**
     * 回收站
     */
    public function trash()
    {
        $data = $this->model->where("isdel", 1)->field('id,title,status,pubtime')->order('id desc')->paginate();

        $this->assign('data', $data);

        return $this->fetch();
    }

    /**
     * 恢复文章
     */
    public function restore()
    {
        if ($this->request->isAjax()) {
            $id =input('post.id');

            if ($this->model->save(['isdel'=>0], ['id'=>$id])) {
                return ['code' => 2];
            } else {
                return ['code' => 0];
            }
        }
    }

    /**
     * 数据库删除
     */
    public function realDel()
    {
        if ($this->request->isAjax()) {
            $id =input('post.id');

            if ($this->model->destroy($id)) {
                return ['code' => 2];
            } else {
                return ['code' => 0];
            }
        }
    }

    public function add()
    {
        if ($this->request->isPOST()) {
            $param = $this->request->param();

            $title = isset($param['title']) ? trim($param['title']) : '';

            if (empty($title)) {
                $this->error('标题不可为空');
            }
            if ($this->existitle($title)) {
                $this->error('标题不可为重复');
            }

            $cid = isset($param['cid']) ? intval($param['cid']) : 0;
            $summary = isset($param['summary']) ? trim($param['summary']) : "";
            $content_md = isset($param['content_md']) ? trim($param['content_md']) : "";
            $pubtime = time();

            try {
                $this->model->save([
                    'cid'   => $cid,
                    'title' => $title,
                    'summary' => $summary,
                    'content_md' => $content_md,
                    'pubtime' => $pubtime,
                ]);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }
            $this->success('添加成功', '/blog_article/index');
        } else {
            $this->assign('categories', $this->categories);

            return $this->fetch();
        }
    }
    
    /**
     * 查询 title 是否存在
     */
    public function existitle($title = null, $id = null)
    {
        if ($id) {
            $result = $this->model->where('title', $title)->where('id', '<>', $id)->find();
        } else {
            $result = $this->model->where('title', $title)->find();
        }
        return $result;
    }

    public function title()
    {
        $title = $this->request->param('title');
        $id = $this->request->has('id') ? $this->request->param('id') : null;

        $res = $this->existitle($title, $id);

        if ($res==false) {
            return ['code'=>1];
        } else {
            return ['code'=>0];
        }
    }
   
    public function edit($id = null)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // var_dump($param);
            // exit();
            $title = isset($param['title']) ? trim($param['title']) : '';
            if (empty($title)) {
                $this->error('标题不可为空');
            }

            if ($this->existitle($title, $id)) {
                $this->error('标题不可为重复');
            }
            
            $cid = isset($param['cid']) ? intval($param['cid']) : 0;
            $summary = isset($param['summary']) ? trim($param['summary']) : "";
            $content_md = isset($param['content_md']) ? trim($param['content_md']) : "";
            
            try {
                $this->model->save([
                    'cid'   => $cid,
                    'title' => $title,
                    'summary' => $summary,
                    'content_md' => $content_md,
                ], ['id'=>$id]);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }
            $this->success('修改成功', '/blog_article/index');
        } else {
            $data = $this->model->find($id);

            if (!$data) {
                $this->error('文章不存在');
            }
            $this->assign('data', $data);
            $this->assign('categories', $this->categories);
            
            return $this->fetch();
        }
    }
}
